<template>
    <van-list 
    v-model="loading" 
    :finished="finished" 
    finished-text="没有更多了"
    :error.sync="error"
    :immediate-check="false"
    error-text="请求失败，点击重新加载"
    @load="onLoad">
    
    <comment-item v-for="(item, index) in list" 
      :key="index" 
      :comment="item"
      @reply-click="$emit('reply-click',$event)"
    />
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props:{
    source:{
      type:[Number,String,Object],
      required:true
    },
    list:{
      type:Array,
      default:() =>[]
    },
    type:{
      type:String,
      validator(value){
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data(){
    return{
      // list:[],
      loading:false,
      finished:false,
      offset:null,
      limit:10,
      error:false
    }
  },
  created(){
    this.loading =true
    this.onLoad()
  },
  methods:{
    async onLoad(){
      try{
        // 1.请求获取数据
        const { data } = await getComments({
          type:this.type,
          source:this.source.toString(),
          offset:this.offset,
          limit: this.limit
        })
        // 2. 将数据添加到列表中
        const { results } = data.data
        this.list.push(...results)

        // 把文章评论的总数量传递给外部
        this.$emit('onload-success', data.data)

        // 3. 将 loading 设置为 false
        this.loading = false

        // 4. 判断是否还有数据
        if(results.length){
          this.offset = data.data.last_id
        }else{
          this.finished = true
        }
      }catch(error){
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>